package ui;
import data.*;
import commProtocol.*;
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import cont.*;

public class ChatGUI extends javax.swing.JFrame implements Observer {

    private ChatController controller;
    private String fname;

   /** Creates new form ChatGUI */
    public ChatGUI() throws SocketException, IOException {
        initComponents();
        controller = new ChatController();

                /* création de la liste*/
        ListContacts list = new ListContacts(new HashtableAdapter());
        //GUI s'ajoute dans la liste des observateur de la liste
        list.addObserver(this);

        // on va pouvoir se reconnecter
        pseudo.setEnabled(true);
        connect.setEnabled(true);

        // on ne peut plus envoyer ou recevoir de messsage
        chat.setEnabled(false);
        contacts_selec.setEnabled(false);
        listcontacts.setEnabled(false);
        file.setEnabled(false);
        send.setEnabled(false);
        send_file.setEnabled(false);
        disconnect.setEnabled(false);
        chat_label.setEnabled(false);
        file_label.setEnabled(false);
        contact_label.setEnabled(false);
        contact_label_selec.setEnabled(false);
        path_file.setEnabled(false);

        this.pack();
        this.setVisible(true);
    }

    //true si ajout du contact, false si suppression
    public void update(Contact contact, boolean action) {
        //réaffiche la bonne liste des contact
        if(action == true){
            listcontacts.add(contact.getLogin());
        }
        else{
            listcontacts.remove(contact.getLogin());
        }
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        username_label = new javax.swing.JLabel();
        pseudo = new javax.swing.JTextField();
        connect = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        chat_label = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        chat = new javax.swing.JTextArea();
        file_label = new javax.swing.JLabel();
        contact_label = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        send = new javax.swing.JButton();
        disconnect = new javax.swing.JButton();
        listcontacts = new java.awt.List();
        contacts_selec = new java.awt.List();
        send_file = new javax.swing.JButton();
        contact_label_selec = new javax.swing.JLabel();
        file = new javax.swing.JButton();
        path_file = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        username_label.setText("Nom d'utilisateur :");

        pseudo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pseudoActionPerformed(evt);
            }
        });

        connect.setText("Connect");
        connect.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                connectMouseClicked(evt);
            }
        });
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        chat_label.setText("Chat :");

        chat.setColumns(20);
        chat.setRows(5);
        chat.setText("Entrez votre texte");
        chat.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                chatMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(chat);

        file_label.setText("File :");

        contact_label.setText("Contacts connected :");

        jScrollPane3.setViewportView(jList2);

        send.setText("Send text");
        send.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                sendMouseClicked(evt);
            }
        });
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });

        disconnect.setText("Disconnect");
        disconnect.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                disconnectMouseClicked(evt);
            }
        });
        disconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnectActionPerformed(evt);
            }
        });

        listcontacts.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listcontactsMouseClicked(evt);
            }
        });

        send_file.setText("Send file");
        send_file.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                send_fileMouseClicked(evt);
            }
        });
        send_file.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                send_fileActionPerformed(evt);
            }
        });

        contact_label_selec.setText("Contacts choosen :");

        file.setText("file's address");
        file.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fileMouseClicked(evt);
            }
        });

        path_file.setText("chemin du fichier sélectionné");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(username_label)
                        .addGap(18, 18, 18)
                        .addComponent(pseudo, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40)
                        .addComponent(connect)
                        .addGap(18, 18, 18)
                        .addComponent(disconnect))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(chat_label)
                                    .addComponent(file_label))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(path_file, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
                                    .addComponent(file, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(8, 8, 8))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(listcontacts, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(contact_label, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(68, 68, 68)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(contacts_selec, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(contact_label_selec, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(send, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(send_file, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(20, 20, 20)))
                                .addGap(56, 56, 56)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(358, 358, 358)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(username_label)
                    .addComponent(pseudo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect)
                    .addComponent(disconnect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(chat_label))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(file)
                    .addComponent(file_label))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(path_file, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(121, 121, 121)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(206, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(contact_label, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(contact_label_selec, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(contacts_selec, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(listcontacts, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(send, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(send_file, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void pseudoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pseudoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_pseudoActionPerformed

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_connectActionPerformed

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_sendActionPerformed

    private void disconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_disconnectActionPerformed

    private void chatMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_chatMouseClicked
        // TODO add your handling code here:
        chat.setText(null);
    }//GEN-LAST:event_chatMouseClicked

    //lorsqu'on clique sur connect
    private void connectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_connectMouseClicked
       if(!(pseudo.getText()).equalsIgnoreCase("") ){
           controller.connect(pseudo.getText());

           //on est connecté, on ne peut pas se reconnecter
           pseudo.setEnabled(false);
           connect.setEnabled(false);

            // on ne peut envoyer ou recevoir de messsage
            chat.setEnabled(true);
            contacts_selec.setEnabled(true);
            listcontacts.setEnabled(true);
            file.setEnabled(true);
            send.setEnabled(true);
            send_file.setEnabled(true);
            disconnect.setEnabled(true);
            chat_label.setEnabled(true);
            file_label.setEnabled(true);
            contact_label.setEnabled(true);
            contact_label_selec.setEnabled(true);
            path_file.setEnabled(false);
       }
    }//GEN-LAST:event_connectMouseClicked
    //lorsqu'on clique sur send text
    private void sendMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sendMouseClicked

        //création d'une liste de contacts
        ArrayList<String> list_selec = new ArrayList<String>();
        int i;
        for(i=0 ; i < contacts_selec.getItemCount() ; i++){
            list_selec.add(contacts_selec.getItem(i));
        }        
        controller.envoie_message(chat.getText(), list_selec);

        //on efface le texte qui avait été écrit
        chat.setText("");
    }//GEN-LAST:event_sendMouseClicked

    private void send_fileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_send_fileMouseClicked

        // ne se lance que si un fichier est bien sélectionné
        if(!fname.equalsIgnoreCase("")){

            //création d'une liste de contacts
            ArrayList<String> list_selec = new ArrayList<String>();
            int i;
            for(i=0 ; i < contacts_selec.getItemCount() ; i++){
                list_selec.add(contacts_selec.getItem(i));
            }
            controller.envoie_message(fname, list_selec);

            //on efface le chemin qui avait été sélectionné
            fname = "";
            path_file.setText("chemin du fichier sélectionné");
        }
    }//GEN-LAST:event_send_fileMouseClicked

    private void send_fileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_send_fileActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_send_fileActionPerformed

    private void disconnectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_disconnectMouseClicked
        // déconnection demandée
        controller.disconnect();

        //on efface le texte qui avait été écrit
        chat.setText("");
        //on efface le chemin qui avait été sélectionné
        fname = "";
        path_file.setText("chemin du fichier sélectionné");

        // on va pouvoir se reconnecter
        pseudo.setEnabled(true);
        connect.setEnabled(true);
        
        // on ne peut plus envoyer ou recevoir de messsage
        chat.setEnabled(false);
        contacts_selec.setEnabled(false);
        listcontacts.setEnabled(false);
        file.setEnabled(false);
        send.setEnabled(false);
        send_file.setEnabled(false);
        disconnect.setEnabled(false);
        chat_label.setEnabled(false);
        file_label.setEnabled(false);
        contact_label.setEnabled(false);
        contact_label_selec.setEnabled(false);
        path_file.setEnabled(false);
    }//GEN-LAST:event_disconnectMouseClicked

    private void fileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileMouseClicked
       // chooser = new Path_file();
       JFileChooser choser = new JFileChooser();//création dun nouveau filechooser
       choser.setApproveButtonText("Choix du fichier..."); //intitulé du bouton
       choser.showOpenDialog(null); //affiche la boite de dialogue
       if (choser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
            fname = choser.getSelectedFile().getAbsolutePath(); // récupère le path
            
       }
       path_file.setEnabled(true);
       path_file.setText(fname);
    }//GEN-LAST:event_fileMouseClicked

    private void listcontactsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listcontactsMouseClicked

        String pseudo_selec = listcontacts.getItem(listcontacts.getSelectedIndex());
        int i;
        boolean present = false;

        // chercherche si le contact est déjà présent dans la liste
        if(!(pseudo_selec.equalsIgnoreCase(""))){

            for(i= 0 ; i < contacts_selec.getItemCount() ; i++){
                if((contacts_selec.getItem(i).equalsIgnoreCase(pseudo_selec))){
                    present = true;
                }
            }

            // si le contact n'est pas déjà présent
            if(present == false){
                contacts_selec.add(listcontacts.getItem(listcontacts.getSelectedIndex()));
            }
       }
    }//GEN-LAST:event_listcontactsMouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new ChatGUI().setVisible(true);
                } catch (SocketException ex) {
                    Logger.getLogger(ChatGUI.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(ChatGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea chat;
    private javax.swing.JLabel chat_label;
    private javax.swing.JButton connect;
    private javax.swing.JLabel contact_label;
    private javax.swing.JLabel contact_label_selec;
    private java.awt.List contacts_selec;
    private javax.swing.JButton disconnect;
    private javax.swing.JButton file;
    private javax.swing.JLabel file_label;
    private javax.swing.JList jList2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private java.awt.List listcontacts;
    private javax.swing.JTextField path_file;
    private javax.swing.JTextField pseudo;
    private javax.swing.JButton send;
    private javax.swing.JButton send_file;
    private javax.swing.JLabel username_label;
    // End of variables declaration//GEN-END:variables



}
